package com.example.shiro;

import com.alibaba.fastjson.JSON;
import com.example.utils.Message;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class ShiroRoleFilter extends PermissionsAuthorizationFilter {

    //Shiro 没有权限失败返回JSON
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {
            //跳转至登录页
            saveRequestAndRedirectToLogin(request, response);
        } else {
            //给前端提示无接口访问权限的错误码
            saveRequestAndReturnApiAccessError(request, response);
        }
        return false;
    }

    private void saveRequestAndReturnApiAccessError(ServletRequest request, ServletResponse response) {
        saveRequest(request);
        Message message = new Message(888,"未授权","");
        try {
            flushMsgStrToClient(response, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
//        JsonResult jsonResult = new JsonResult(0, "登陆时间过长，请重新登陆", null);
        Message message = new Message(999,"登陆时间过长，请重新登陆","");
        try {
            flushMsgStrToClient(response, message);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }


    public static void flushMsgStrToClient(ServletResponse response, Object object)
            throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        Message message = new Message(888,"未授权","");
        String json = JSON.toJSONString(message);
        response.getWriter().print(json);
        response.getWriter().flush();
    }
}
